import random
import matplotlib.pyplot as plt
import numpy as np
from collections import Counter

def set_chinese_font():
    """设置中文字体"""
    plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

set_chinese_font()


def probability_demo():
    # 模拟抛硬币
    def coin_toss_simulation(n_tosses):
        results = [random.choice(['正面', '反面']) for _ in range(n_tosses)]
        return results
    
    # 模拟掷骰子
    def dice_roll_simulation(n_rolls):
        results = [random.randint(1, 6) for _ in range(n_rolls)]
        return results
    
    # 创建图形
    fig, axes = plt.subplots(1, 2, figsize=(12, 5))
    
    # 抛硬币实验
    coin_results = coin_toss_simulation(1000)
    coin_counts = Counter(coin_results)
    
    axes[0].bar(coin_counts.keys(), coin_counts.values(), color=['skyblue', 'lightcoral'])
    axes[0].set_title('抛硬币实验 (1000次)')
    axes[0].set_ylabel('频数')
    
    # 计算理论概率和实际频率
    theoretical_prob = 0.5
    actual_freq_heads = coin_counts['正面'] / 1000
    actual_freq_tails = coin_counts['反面'] / 1000
    
    print(f"抛硬币实验:")
    print(f"  正面理论概率: {theoretical_prob:.3f}, 实际频率: {actual_freq_heads:.3f}")
    print(f"  反面理论概率: {theoretical_prob:.3f}, 实际频率: {actual_freq_tails:.3f}")
    
    # 掷骰子实验
    dice_results = dice_roll_simulation(1000)
    dice_counts = Counter(dice_results)
    
    # 按骰子点数排序
    dice_points = sorted(dice_counts.keys())
    dice_frequencies = [dice_counts[point] for point in dice_points]
    
    axes[1].bar(dice_points, dice_frequencies, color='lightgreen', edgecolor='black')
    axes[1].set_title('掷骰子实验 (1000次)')
    axes[1].set_xlabel('骰子点数')
    axes[1].set_ylabel('频数')
    
    # 计算理论概率和实际频率
    theoretical_prob_dice = 1/6
    print(f"\n掷骰子实验:")
    for point in dice_points:
        actual_freq = dice_counts[point] / 1000
        print(f"  点数{point}: 理论概率 {theoretical_prob_dice:.3f}, 实际频率 {actual_freq:.3f}")
    
    plt.tight_layout()
    plt.show()

probability_demo()